package com.zhunaer.dao.impl;

import com.zhunaer.dao.RoomDao;
import com.zhunaer.entity.Room;
import com.zhunaer.utils.JDBCUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;

/**
 * 房型数据访问对象实现类
 *
 * <p>提供房型数据的持久化操作，包括：
 * <ul>
 *   <li>房型信息的增删改查</li>
 *   <li>房型库存管理</li>
 *   <li>店铺房型查询</li>
 * </ul>
 */
public class RoomDaoImpl implements RoomDao {

    /**
     * 创建新房型
     *
     * @param room 包含房型信息的实体对象
     * @return 返回生成的房型ID，创建失败返回-1
     * @throws RuntimeException 当数据库操作失败时抛出
     */
    @Override
    public int createRoom(Room room) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();
            String sql = "INSERT INTO rooms(shop_id, room_type, bed_type, price, stock, room_keywords) VALUES(?,?,?,?,?,?)";
            pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            pstmt.setInt(1, room.getShopId());
            pstmt.setString(2, room.getRoomType());
            pstmt.setString(3, room.getBedType());
            pstmt.setBigDecimal(4, room.getPrice());
            pstmt.setInt(5, room.getStock());
            pstmt.setString(6, room.getRoomKeywords());

            int affectedRows = pstmt.executeUpdate();
            if (affectedRows > 0) {
                rs = pstmt.getGeneratedKeys();
                if (rs.next()) {
                    return rs.getInt(1);
                }
            }
            return -1;
        } catch (SQLException e) {
            throw new RuntimeException("创建房型失败", e);
        } finally {
            JDBCUtils.close(conn, pstmt, rs);
        }
    }

    /**
     * 更新房型信息
     *
     * @param room 包含更新信息的房型实体对象
     * @return 受影响的行数
     * @throws RuntimeException 当数据库操作失败时抛出
     */
    @Override
    public int updateRoom(Room room) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = JDBCUtils.getConnection();
            String sql = "UPDATE rooms SET room_type=?, bed_type=?, price=?, stock=?, room_keywords=? WHERE room_id=?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, room.getRoomType());
            pstmt.setString(2, room.getBedType());
            pstmt.setBigDecimal(3, room.getPrice());
            pstmt.setInt(4, room.getStock());
            pstmt.setString(5, room.getRoomKeywords());
            pstmt.setInt(6, room.getRoomId());
            return pstmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("更新房型失败", e);
        } finally {
            JDBCUtils.close(conn, pstmt, null);
        }
    }

    /**
     * 删除指定房型
     *
     * @param roomId 要删除的房型ID
     * @return 受影响的行数
     * @throws RuntimeException 当数据库操作失败时抛出
     */
    @Override
    public int deleteRoom(int roomId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = JDBCUtils.getConnection();
            String sql = "DELETE FROM rooms WHERE room_id=?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, roomId);
            return pstmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("删除房型失败", e);
        } finally {
            JDBCUtils.close(conn, pstmt, null);
        }
    }

    /**
     * 根据ID查询房型详情
     *
     * @param roomId 要查询的房型ID
     * @return 房型实体对象，未找到返回null
     * @throws RuntimeException 当数据库操作失败时抛出
     */
    @Override
    public Room findRoomById(int roomId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();
            String sql = "SELECT * FROM rooms WHERE room_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, roomId);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                Room room = new Room();
                room.setRoomId(rs.getInt("room_id"));
                room.setShopId(rs.getInt("shop_id"));
                room.setRoomType(rs.getString("room_type"));
                room.setBedType(rs.getString("bed_type"));
                room.setPrice(rs.getBigDecimal("price"));
                room.setStock(rs.getInt("stock"));
                room.setRoomKeywords(rs.getString("room_keywords"));
                room.setCreatedAt(new Date(rs.getTimestamp("created_at").getTime()));
                return room;
            }
            return null;
        } catch (SQLException e) {
            throw new RuntimeException("查询房型失败", e);
        } finally {
            JDBCUtils.close(conn, pstmt, rs);
        }
    }

    /**
     * 查询指定店铺的所有房型
     *
     * @param shopId 店铺ID
     * @return 房型列表，包含该店铺所有房型信息
     * @throws RuntimeException 当数据库操作失败时抛出
     */
    @Override
    public List<Room> findRoomsByShop(int shopId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Room> rooms = new ArrayList<>();
        try {
            conn = JDBCUtils.getConnection();
            String sql = "SELECT * FROM rooms WHERE shop_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, shopId);
            rs = pstmt.executeQuery();

            while (rs.next()) {
                Room room = new Room();
                room.setRoomId(rs.getInt("room_id"));
                room.setShopId(rs.getInt("shop_id"));
                room.setRoomType(rs.getString("room_type"));
                room.setBedType(rs.getString("bed_type"));
                room.setPrice(rs.getBigDecimal("price"));
                room.setStock(rs.getInt("stock"));
                room.setRoomKeywords(rs.getString("room_keywords"));
                room.setCreatedAt(new Date(rs.getTimestamp("created_at").getTime()));
                rooms.add(room);
            }
            return rooms;
        } catch (SQLException e) {
            throw new RuntimeException("查询店铺房型失败", e);
        } finally {
            JDBCUtils.close(conn, pstmt, rs);
        }
    }

    /**
     * 更新房型库存
     *
     * @param roomId 房型ID
     * @param quantity 库存变化量（正数表示增加，负数表示减少）
     * @return 受影响的行数
     * @throws RuntimeException 当数据库操作失败时抛出
     */
    @Override
    public int updateStock(int roomId, int quantity) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = JDBCUtils.getConnection();
            String sql = "UPDATE rooms SET stock = stock + ? WHERE room_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, quantity);
            pstmt.setInt(2, roomId);
            return pstmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("更新库存失败", e);
        } finally {
            JDBCUtils.close(conn, pstmt, null);
        }
    }
}